#coding:utf-8

from es_store import initEsDocumentStore

import json
import urllib

SCORE_URI = 'http://0.0.0.0:8989/score'

def get_score(title,content,scorer='1',uri=SCORE_URI):
    #text = (title+content)
    #text = text.lower()
    #if isinstance(text,unicode):
    #    text = text.encode('utf-8')
    #data = {'data':text}
    if isinstance(title,unicode):
        title = title.encode('utf-8')
    if isinstance(content,unicode):
        content = content.encode('utf-8')
    data = {'title':title,'content':content,'score':scorer}
    data = urllib.urlencode(data)
    rp = urllib.urlopen(uri,data)
    res = rp.read()
    return json.loads(res)

def get_keyword(i,scorer="1"):
    es = initEsDocumentStore()
    r = es.get(i)

    title = r['cut_title']
    content = r['cut_content']

    print i,title

    vs = get_score(title,content,scorer)
    #print len(vs)
    #for v,s in vs.items():
    #    print v,s
    return vs

def test_case_score(location1,location2,scorer):
    f1 = open(location1,mode='r')
    f2 = open(location2,mode='w')

    for line in f1:
        n = json.loads(line)

        v1 = get_score(n['ct1'],n['cc1'],scorer)
        v2 = get_score(n['ct2'],n['cc2'],scorer)
        
        r = {}
        r['i1'] = n['i1']
        r['v1'] = v1
        r['i2'] = n['i2']
        r['v2'] = v2

        line = json.dumps(r,ensure_ascii=False)
        f2.write(line.encode('utf-8')+'\n')

    f1.close()
    f2.close()

from cos import scut

def test_keyword():
    ii = "4307075141-4348420561"
    ii = "4200443125-4200341795"
    ii = "4399137582-4403474237"
    i = ii.split('-')[0]
    vs = get_keyword(i,"8")
    vs = scut(vs,30)
    print json.dumps(vs,ensure_ascii=False)
    i = ii.split('-')[1]
    vs = get_keyword(i,"8")
    vs = scut(vs,30)
    print json.dumps(vs,ensure_ascii=False)




if __name__ == '__main__':

    print 'Hi'

    #test_keyword()

    location1 = 'data/issue.v.txt'
    location2 = 'data/issue.vv.txt'
    test_case_score(location1,location2,'2')

